package com.wengzw.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.wengzw.gateway.common.ResponseResult;
import com.wengzw.gateway.common.ResultCode;
import com.wengzw.gateway.config.JwtProperties;
import com.wengzw.gateway.utils.JWTUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import com.wengzw.gateway.common.Constant;


import java.util.LinkedHashMap;
import java.util.Map;

import static com.wengzw.gateway.common.Constant.*;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    private final JwtProperties jwtProperties;

    public TokenFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        String token = serverHttpRequest.getHeaders().getFirst(Constant.TOKEN);
        // 白名单以外的请求中存在token
        if (StringUtils.hasLength(token)) {
            Map<String, Object> stringObjectMap = JWTUtil.verifyJavaWebToken(token, jwtProperties.getSecretKey());
            if (stringObjectMap == null || !stringObjectMap.containsKey(TOKEN_USER_INFO)) {
                return getUnAuthorizedMono(serverHttpResponse);
            }
            LinkedHashMap<String, Object> userDetails = (LinkedHashMap) stringObjectMap.get(TOKEN_USER_INFO);
            ServerHttpRequest mutableReq = serverHttpRequest.mutate().header(HEADER_USER, (String) userDetails.get(TOKEN_USER_INFO_USERNAME)).build();
            ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
            return chain.filter(mutableExchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> getUnAuthorizedMono(ServerHttpResponse serverHttpResponse) {
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ResponseResult<Object> responseResult = ResponseResult.error(ResultCode.UNAUTHORIZED.getMsg());
        DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(responseResult).getBytes());
        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
